const Post = require('../models/Post')
const mongoose = require('mongoose')
const utils = require('../utils/index')
// 响应的json数据
const responseData = {}


// 显示文章列表
exports.list = (req, res) => {
  const page = req.params.page || 1  // 当前页
  const limit = 2 // 每页显示几条数据
  const skip = (page - 1) * limit // 第page页从第几条开始显示
  let count = 0   // 数据总数量
  let maxpage = 0 // 最大页码
  Promise.all([
    Post.countDocuments(),
    Post.find()
      .populate('author_id','username')
      .limit(limit)
      .lean()
      .skip(skip)
      .sort({'create_at':-1})
  ]).then(result => {
    count = result[0]
    maxpage = Math.ceil(count / limit)
    responseData.code = 200
    responseData.msg = 'success'
    responseData.data = {}  // 这一步是必要的,不然下面的操作会报Cannot set property 'list' of undefined
    responseData.data.list = result[1]
    responseData.data.totalPage = maxpage
    return res.json(responseData)
  }).catch(err => {
    console.log(err)
    responseData.code = 500
    responseData.msg = '服务出现异常'
    responseData.data = {}
    return res.json(responseData)
  })
}
// 显示文章详情
exports.detail = (req, res) => {
  const post_id = req.params.post_id || req.body.post_id
  Post.findOne({
    _id: mongoose.Types.ObjectId(post_id)
  }).populate({
    path:'author_id',
    select:'username'
  }).then((postInfo)=>{
    if(postInfo) {
      responseData.code = 200
      responseData.msg = 'success'
      responseData.data = postInfo
    } else {
      responseData.data = 404
      responseData.msg = "文章未找到"
      responseData.data = {}
    }
    res.json(responseData)
  })
}

// 添加文章
exports.add = (req, res) => {
  const author_id = req.body.uid || ''
  const title = req.body.title || ''
  const content = req.body.content || ''

  Post.findOne({
    title: title
  }).then(postInfo => {
    if(postInfo) {
      responseData.code = 500
      responseData.msg = '文章标题重复'
      responseData.data = {}
      return
    } else {
      const post = new Post({
        title: title,
        author_id: mongoose.Types.ObjectId(author_id),
        content: content
      })
      return post.save()
    }
  }).then(postInfo => {
    if(postInfo) {
      responseData.code = 200
      responseData.msg = '文章添加成功'
      responseData.data = postInfo
    }
    return res.json(responseData)
  }).catch(err => {
    responseData.code = 500
    responseData.msg = '服务出现异常'
    responseData.data = {}
    return res.json(responseData)
  })
}

// 文章删除
exports.delete =(req, res) => {
  const post_id = req.body.post_id
  const uid = req.body.uid

  Post.deleteOne({
    _id: mongoose.Types.ObjectId(post_id),
    author_id: mongoose.Types.ObjectId(uid)
  }).then(result => {
    if(result.n) {
      responseData.code = 200
      responseData.msg = '删除成功'
      responseData.data = {}
    } else {
      responseData.code = 500
      responseData.msg = '删除失败'
      responseData.data = {}
    }
    return res.json(responseData)
  })
}

// 文章编辑
exports.edit = (req, res) => {
  const post_id = req.body.post_id
  const uid = req.body.uid
  const title = req.body.title
  const content = req.body.content

  Post.findOne({
    _id: mongoose.Types.ObjectId(post_id),
    author_id: mongoose.Types.ObjectId(uid)
  }).then(result => {
    if(result) {
      if(result.title == title) {
        responseData.code = 500
        responseData.msg = '已存在此标题的文章'
        responseData.data = {}
        return
      } else {
        return Post.updateOne({
          _id: mongoose.Types.ObjectId(post_id),
        },{
          title:title,
          content:content,
          update_at: Date.now()
        })
      }
    } else {
      responseData.code = 404
      responseData.msg = '找不到此用户的文章'
      responseData.data = {}
      return
    }
  }).then(result => {
    if(result){
      responseData.code = 200
      responseData.msg = '文章编辑成功'
      responseData.data = {}
    }
    return res.json(responseData)
  }).catch(err => {
    responseData.code = 500
    responseData.msg = '服务出现异常'
    responseData.data = {}
    return res.json(responseData)
  })
}
